;
(function () {
  'use strict';
  angular.module('services.alarmDataAnalysis.multidimensionalAnalysis')
    .service('analysisDataByBusinessService', analysisDataByBusinessService);
  function analysisDataByBusinessService($http, $filter, CoreService, $timeout,CoreLoading) {
    var time = new Date();
    var date = new Date(time.getFullYear(), time.getMonth(), time.getDate() - 1);  //页面时间默认日期的前一天
    //页面参数
    this.params = {
      startTime: date,
      endTime: date,
      provincialCompanyCodes: [],  //省公司code
      alarmType: '告警总数'
    };
    this.businessLineList = [];   //业务线列表
    this.provincialCompanyList = [];   //省公司数据列表
    this.alaDataList = [];  //告警数据集合

    this.alarmType = null;  //告警类型输入框绑定值
    this.showSearchPanel = true;//显示查询面板
    this.hideLittleUp=false;  //隐藏查询面板中向上的小箭头
    this.re = 'false';
    this.showIcon = true;   //控制显示折线和表格的图标
    this.showDataByHourBtn = false;   //控制是否显示按时刻展示数据的变量
    this.viewType = 'chart';//默认折线视图类型
    this.title = null;  //图表和表格显示的标题
    var dayCount = 0; //保存查询数据的总天数
    var chart = null;   //折线图

    var dayCount = 0; //保存查询数据的总天数
    var dataList = [];   //临时数据集合
    this.businessLineNames = [];//图表和表格标题显示业务线名称(所有业务线名称)
    var provincialCompanyNames = [];//(31省)图表和表格标题显示省公司名称
    var cproCompanyNames = [];//(选中省公司名称)
    var that = this;
    var param = {}; //临时参数对象
    /**
     * 隐藏查询面板
     */
    this.hideSearchPanel = function () {
      this.showSearchPanel = false;
    };
    /**
     * 清空页面旧值
     */
    this.reset = function () {
      that.showSearchPanel = true;
      that.hideLittleUp=false;
      that.viewType = 'chart';
      that.params.startTime = date;
      that.params.endTime = date;
      that.params.alarmType = '告警总数';
      that.params.provincialCompanyCodes = [];
      that.alarmType = null;
      that.alaDataList = [];
      that.dataList = [];
      that.showIcon = false;
      that.businessLineNames = [];//图表和表格标题显示业务线名称
      that.businessLineList = [];   //业务线列表
      that.provincialCompanyList = [];   //省公司数据列表
    };
    /**
     * 选中告警总数  告警类型输入框清空
     */
    this.resetAlarmType = function () {
      that.alarmType = null;
    };
    this.initSelectMenu = function () {
      //获取业务线
      $http.get('/sas/common/businessLineQuery')
        .then(function (res) {
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            that.businessLineList = res.data.data;
          } else {
            CoreService.dialog('查询无数据');
          }
        });

      //获取省公司
      $http.get('/sas/common/provinceQuery')
        .then(function (res) {
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            that.provincialCompanyList = res.data.data;
            that.search();
          } else {
            CoreService.dialog('查询无数据');
          }
        });
      
    };

    /**
     * 查询 告警数据分业务进行分析对比
     */
    this.sendData = null;
    this.search = function () {
      that.hideLittleUp=false;
      //收起查询面板
      if (!that.showSearchPanel) {
        that.showSearchPanel = true;
        return;
      }
      if ((that.params.alarmType === '1' && that.alarmType == null) || (that.params.alarmType === '1' && that.alarmType === '')) {
        that.PageDisplayStyle();
        CoreService.dialog('请输入有效的告警类型');
        return;
      }
      //时间粒度为天时，最多只能查询31天的数据
      var endTime = that.params.endTime.getTime();
      var startTime = that.params.startTime.getTime();
      dayCount = (endTime - startTime) / 1000 / 60 / 60 / 24;
      if (dayCount > 59) {
        CoreService.dialog('只能查询60天内的数据！');
        return;
      }
      CoreLoading.setState(true);
      //copy页面参数 格式化参数
      param = angular.copy(that.params);
      param.startTime = $filter('date')(param.startTime, 'yyyy-MM-dd');
      param.endTime = $filter('date')(param.endTime, 'yyyy-MM-dd');
      if (param.alarmType === '1') {
        param.alarmType = that.alarmType;
      } else if (param.alarmType === '告警总数') {
        that.alarmType = '';
      }
      //参数省公司传code
      param.provincialCompanyCodes.length || (param.provincialCompanyCodes = that.provincialCompanyList);
      //(选中省公司名称)
      cproCompanyNames = param.provincialCompanyCodes.map(function (obj) {
        return obj.provinceName;
      });
      param.provincialCompanyCodes = param.provincialCompanyCodes.map(function (obj) {
        return obj.provinceCode;
      });
      //(31)省公司 根据Code获取Name,图表展示标题所需 图表横轴坐标展示
      provincialCompanyNames = [];
      angular.forEach(that.provincialCompanyList, function (pro) {
        provincialCompanyNames.push(pro.provinceName);
      });

      //业务线 根据Code获取Name,图表展示标题所需
      that.businessLineNames = [];
      angular.forEach(that.businessLineList, function (obj) {
        that.businessLineNames.push(obj.businessLineName);
      });
      //页面标题显示方式
      if (param.alarmType === '告警总数') {
        if (param.startTime === param.endTime) {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 各业务线告警数量统计';
        } else {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 各业务线告警数量统计';
        }

      } else {
        if (param.startTime === param.endTime) {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 告警类型为 ' + param.alarmType + ' 各业务线告警数量统计';
        } else {
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 告警类型为 ' + param.alarmType + ' 各业务线告警数量统计';
        }

      }
      $http.post('/sas/alarmData/analysisByBusiness/query', param)
        .then(function (res) {
          that.showSearchPanel = false;   //收缩查询面板
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            CoreLoading.setState(false);
            dataList = res.data.data;
            that.changeViewType();  //默认显示折线图表
            that.showIcon = true; //显示表格和折线图标
          } else {
            CoreLoading.setState(false);
            that.PageDisplayStyle();
            CoreService.dialog('查询无数据');
          }

        });

    };

    //初始化折线图数据
    function initChart() {
      chart = echarts.init(document.getElementById('analysisDataByBusinessChart'));
      var option = {
        animation:false,
        title: {
          text: that.title,
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: function (param) {
            return param.name + '<br/>' + param.seriesName + ': ' + param.value + '条';
          }
        },
        legend: {data: ['告警数量'], x: 'right', y: 'center', orient: 'vertical'},
        xAxis: [{type: 'category', data: [], axisLabel: {rotate: 45,}, splitLine: {show: false}}],
        yAxis: [
          {
            name: '告警数量（条）',
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [{
          name: '告警数量',
          type: 'bar',
          data: []
        }],
        grid: {x: '104', x2: '128'}
      };


      var x = that.businessLineNames;  //横轴显示所有业务线
      option.xAxis[0].data = x;

      angular.forEach(x, function (businessLineName) {
        var alarNum = 0;
        angular.forEach(cproCompanyNames, function (provinceName) {
          angular.forEach(dataList, function (obj) {
            if (obj.businessLineName === businessLineName) {
              alarNum = obj.alarmNum;
            }
          });
        });
        option.series[0].data.push(alarNum);
      });
      chart.setOption(option);
      $timeout(function(){
        that.sendData = onSubmit();   //导出的图表生成
      },1000);
    };

    /**初始化表格*/
    function initTable() {
      var list = [];
      var row = [];
      var time = $filter('date')(param.startTime, 'yyyyMMdd') + '-' + $filter('date')(param.endTime, 'yyyyMMdd')
      var alarmType = '';
      if (param.alarmType === '告警总数') {
        alarmType = '全部';
      } else {
        alarmType = param.alarmType;
      }
      var provinceNames = '';
      var businessName = '';
      var alarmNumTotal = 0;
      if (param.provincialCompanyCodes.length === 32) {
        provinceNames = '全部';
      } else {
        angular.forEach(cproCompanyNames, function (provinceName) {
          provinceNames += provinceName + ',';
        });
        provinceNames = provinceNames.substring(0, provinceNames.length - 1);
      }
      angular.forEach(that.businessLineNames, function (businessLineName) {
        businessName = businessLineName;
        alarmNumTotal = 0;
          angular.forEach(dataList, function (data) {
            //debugger;
            if (data.businessLineName === businessLineName) {
              alarmNumTotal = data.alarmNum;
            }
        });
        row = [time, provinceNames, alarmType, businessName, alarmNumTotal];
        list.push(row);
      });
      that.alaDataList = list;
    };

    //查询无数据时页面的样式
    this.PageDisplayStyle = function () {
      //debugger;
      that.title = '';
      that.viewType = 'chart';
      that.showSearchPanel = true;   //显示查询面板
      that.hideLittleUp=true;
      that.showIcon = false;  //隐藏表格和折线图标
      dataList = [];  //数据清空
      that.alaDataList = [];
      chart && chart.clear();  //折线图表数据清空
    }
    //控制显示折线或者表格
    this.changeViewType = function (type) {
      initChart();
      var ta = document.getElementById('ta');
      var cha = document.getElementById('cha');
      that.viewType = type || that.viewType;
      if (that.viewType === 'chart') {
        $timeout(initChart, 0);
        ta.style.backgroundColor = "";
        cha.style.backgroundColor = "#2196F3";
      } else if (that.viewType === 'table') {
        ta.style.backgroundColor = "#2196F3";
        cha.style.backgroundColor = "";
        initTable();
      }
    };
    /**导出excel*/
    function onSubmit () {
      var data = {
        startTime: $filter('date')(param.startTime, 'yyyy-MM-dd'),
        endTime: $filter('date')(param.endTime, 'yyyy-MM-dd'),
        title: that.title,
        provincialCompanyCodes: param.provincialCompanyCodes,
        alarmType: param.alarmType,
        base64s: [chart.getDataURL('png').split(',')[1]],
      };
      return JSON.stringify(data);
    };
  }

  analysisDataByBusinessService.$inject = ['$http', '$filter', 'CoreService', '$timeout','CoreLoading'];
})
();